<template>
  <div class="Upload">
    <el-card>
      <h3><span class="tag"></span> 上传管理</h3>
      <div class="box">
        <el-upload
          class="upload-demo"
          :show-file-list="false"
          action
          :http-request="() => {}"
          multiple
          :before-upload="beforeUploadVideo"
        >
          <!-- <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          <em style="color: #c0c0c0">{{ "点击上传" }}</em>
          <div style="color: #c0c0c0; font-size: 12px">
            {{ "只能上传MP4文件，且不超过2GB" }}
          </div>
        </div> -->
          <el-button size="small" class="btn">选择文件</el-button>
        </el-upload>
        <el-button
          size="small"
          type="success"
          plain
          @click="onStartUpload"
          :loading="btnloading"
          >开始上传</el-button
        >
        <el-button size="small" type="info" plain @click="exportExcel"
          >导出成功信息</el-button
        >
        <el-button size="small" type="warning" plain @click="clear"
          >清空列表</el-button
        >
        <!-- <el-button size="small" type="warning" plain @click="clear"
          >清空列表</el-button
        > -->
      </div>
      <el-table
        :data="fileList"
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{ background: '#f4f4f5' }"
        tooltip-effect="dark"
        border
      >
        <el-table-column prop="name" label="文件名称">
          <template slot-scope="scope">
            {{ scope.row.file.name }}
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小">
          <template slot-scope="scope">
            <div>{{ scope.row.file.size | filterSize }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="文件类型"> </el-table-column>
        <el-table-column prop="size" label="进度">
          <template slot-scope="scope">
            <el-progress
              :text-inside="true"
              :stroke-width="26"
              :percentage="scope.row.progressBar"
              :format="format"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="上传状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">未开始上传</span>
            <span v-if="scope.row.status == 1" style="color: #409eff"
              >上传中</span
            >
            <span v-if="scope.row.status == 2" style="color: #67c23a"
              >上传成功</span
            >
            <span v-if="scope.row.status == 3" style="color: #f56c6c"
              >上传失败</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="url" label="上传成功地址">
          <template slot-scope="scope">
            {{ scope.row.url }}
          </template>
        </el-table-column>
        <el-table-column prop="url" label="操作" width="350">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="warning"
              plain
              :disabled="scope.row.status != 3"
              @click="reUpload(scope.row, scope.$index)"
              >重新上传</el-button
            >
            <el-button
              :disabled="scope.row.url == ''"
              type="primary"
              plain
              size="small"
              @click="copy(scope.row.url)"
              >复制地址</el-button
            >
            <el-button size="small" @click="delList(scope.row, scope.$index)"
              >删除文件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
export default {
  data() {
    return {
      fileList: [],
      isStartUpload: true,
      uploadIndex: 0, //批量上传时的索引
      btnloading: false,
    };
  },
  methods: {
    //选择文件
    beforeUploadVideo(file) {
      let videFile = {
        file: file,
        progressBar: 0,
        url: "",
        uploadDisabled: false,
        status: 0,
        type: file.name.substring(file.name.lastIndexOf(".") + 1),
      };
      this.fileList.push(videFile);
      console.log(this.fileList);
    },
    //删除列表
    delList(obj, index) {
      if (obj.uploadDisabled) {
        this.$message.error("正在上传中，禁止删除");
        return false;
      } else if (obj.progressBar > 0) {
        this.$message.error("已上传完成，无法删除");
        return false;
      }
      this.$confirm("确定删除该数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.fileList.splice(index, 1);
        })
        .catch(() => {});
    },
    //开始上传
    onStartUpload() {
      if (this.fileList.length == 0) {
        this.$message.error("上传列表不能为空！");
        return false;
      }
      this.onUpload(this.fileList[this.uploadIndex], this.uploadIndex);
      this.isStartUpload = true;
      this.btnloading = true;
    },
    //上传
    async onUpload(file, index) {
      file.uploadDisabled = true;
      file.status = 1;
      let that = this;
      this.progressSeen = true; //进度条显示
      //根据文件类型设置ossToken的type
      let type = 7;
      switch (file.type) {
        case "png":
          type = 0;
          break;
      }
      //请求ossToken
      try {
        await ossToken({
          type,
        }).then((res) => {
          if (res.code == 0) {
            this.dataObj = {
              accessKeyId: res.data.accessKey,
              accessKeySecret: res.data.accessSecret,
              securityToken: res.data.token,
              region: "oss-" + res.data.regionId,
              bucket: res.data.bucket,
            };
          }
        });
        //设置上传文件名
        let path = "/other/";
        switch (type) {
          case 0:
            path = "/img/";
            break;
        }
        let fileNames =
          path +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        console.log(fileNames);
        //配置进度条配置
        const options = {
          progress: function (p, checkpoint) {
            that.fileList[index].progressBar = Number((p * 100).toFixed(0));
            that.tempCheckpoint = checkpoint;
          },
          partSize: 1000 * 1024, //设置分片大小
          timeout: 120000, //设置超时时间
        };
        //开始上传
        client(this.dataObj)
          .multipartUpload(fileNames, file.file, options)
          .then((res) => {
            file.uploadDisabled = false;
            file.status = 2;
            // file.url = res.res.requestUrls[0];
            console.log(res);
            file.url =
              "https://xinyue-static.oss-cn-hangzhou.aliyuncs.com" + fileNames;
            if (that.fileList.length != index + 1) {
              that.uploadIndex++;
              that.onUpload(that.fileList[that.uploadIndex], that.uploadIndex);
            } else {
              this.btnloading = false;
            }
          })
          .catch(() => {
            file.status = 3;
            if (that.fileList.length != index + 1) {
              that.uploadIndex++;
              that.onUpload(that.fileList[that.uploadIndex], that.uploadIndex);
            } else {
              this.btnloading = false;
            }
          });
      } catch {
        file.status = 3;
        if (that.fileList.length != index + 1) {
          that.uploadIndex++;
          that.onUpload(that.fileList[that.uploadIndex], that.uploadIndex);
        } else {
          this.btnloading = false;
        }
      }
    },
    //进度条
    format(percentage) {
      return percentage === 100 ? "上传完成" : `${percentage}%`;
    },
    //清空
    clear() {
      this.$confirm("是否已保存成功信息，再确定？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.fileList = [];
          this.uploadIndex = 0;
        })
        .catch(() => {});
    },
    //导出
    exportExcel() {
      let arr = this.fileList.filter((item) => {
        item.name = item.file.name;
        return item.status == 2;
      });
      if (arr.length == 0) {
        this.$message.error("没有上传成功信息可导出！");
        return;
      }
      console.log(arr);
      const head = ["上传文件名称", "上传路径"];
      const key = ["name", "url"];
      this.$excel(arr, head, key, "上传信息");
    },
    //重新上传
    async reUpload(file) {
      file.uploadDisabled = true;
      file.status = 1;
      let that = this;
      this.progressSeen = true; //进度条显示
      //请求ossToken
      try {
        await ossToken({
          type: 7,
        }).then((res) => {
          if (res.code == 0) {
            this.dataObj = {
              accessKeyId: res.data.accessKey,
              accessKeySecret: res.data.accessSecret,
              securityToken: res.data.token,
              region: "oss-" + res.data.regionId,
              bucket: res.data.bucket,
            };
          }
        });
        //设置上传文件名
        let fileNames =
          "/other/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        console.log(fileNames);
        //配置进度条配置
        const options = {
          progress: function (p, checkpoint) {
            file.progressBar = Number((p * 100).toFixed(0));
            that.tempCheckpoint = checkpoint;
          },
          partSize: 1000 * 1024, //设置分片大小
          timeout: 120000, //设置超时时间
        };
        //开始上传
        client(this.dataObj)
          .multipartUpload(fileNames, file.file, options)
          .then((res) => {
            file.uploadDisabled = false;
            file.status = 2;
            // file.url = res.res.requestUrls[0];
            file.url =
              "https://xinyue-static.oss-cn-hangzhou.aliyuncs.com" + fileNames;
          })
          .catch(() => {
            file.status = 3;
          });
      } catch {
        file.status = 3;
      }
    },
    //复制
    copy(url) {
      let transfer = document.createElement("input");
      document.body.appendChild(transfer);
      transfer.value = url; // 这里表示想要复制的内容
      transfer.focus();
      transfer.select();
      if (document.execCommand("copy")) {
        document.execCommand("copy");
      }
      transfer.blur();
      this.$message.success("复制成功！");
      document.body.removeChild(transfer);
    },
  },
  filters: {
    filterSize(bytes) {
      if (bytes === 0) return "0 B";
      var k = 1024, // or 1024
        sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
        i = Math.floor(Math.log(bytes) / Math.log(k));

      return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
    },
  },
};
</script>

<style lang="less" scoped>
.Upload {
  padding: 20px;
  h3 {
    margin: 0 0 20px;
    display: flex;
    align-items: center;
    .tag {
      display: inline-block;
      width: 5px;
      height: 18px;
      background-color: #7b94d8;
      margin-right: 10px;
    }
  }
  .box {
    display: flex;
  }
}
</style>